#include "drv_can.h"
#include "elog.h"

int stm32_fdcan1_send_message(int chn, uint32_t id, uint8_t *data, int len)
{
    int ret = 0;
    FDCAN_TxHeaderTypeDef TxHeader;

    if (len > 8)
    {
        return -1;
    }

    TxHeader.Identifier = id;                         // 帧ID
    TxHeader.IdType = FDCAN_EXTENDED_ID;              // 扩展帧
    TxHeader.TxFrameType = FDCAN_DATA_FRAME;          // 数据帧
    TxHeader.DataLength = FDCAN_DLC_BYTES_8;          // 数据长度
    TxHeader.ErrorStateIndicator = FDCAN_ESI_PASSIVE; // 错误指示
    TxHeader.BitRateSwitch = FDCAN_BRS_OFF;           // 关闭可变波特率
    TxHeader.FDFormat = FDCAN_CLASSIC_CAN;            // 传统classsic can
    TxHeader.TxEventFifoControl = FDCAN_NO_TX_EVENTS; // 发送时间FIFO控制，不存储
    TxHeader.MessageMarker = 0;                       // 识别消息状态，范围0到0xFF

    // 发送CAN消息
    if (HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan1, &TxHeader, data) != HAL_OK)
    {
        log_e("fdcan1 send faiil.");
        // Error_Handler();
    }
    return ret;
}

int stm32_fdcan2_send_message(int chn, uint32_t id, uint8_t *data, int len)
{
    int ret = 0;
    FDCAN_TxHeaderTypeDef TxHeader;

    if (len > 8)
    {
        return -1;
    }

    TxHeader.Identifier = id;                         // 帧ID
    TxHeader.IdType = FDCAN_EXTENDED_ID;              // 扩展帧
    TxHeader.TxFrameType = FDCAN_DATA_FRAME;          // 数据帧
    TxHeader.DataLength = FDCAN_DLC_BYTES_8;          // 数据长度
    TxHeader.ErrorStateIndicator = FDCAN_ESI_PASSIVE; // 错误指示
    TxHeader.BitRateSwitch = FDCAN_BRS_OFF;           // 关闭可变波特率
    TxHeader.FDFormat = FDCAN_CLASSIC_CAN;            // 传统classsic can
    TxHeader.TxEventFifoControl = FDCAN_NO_TX_EVENTS; // 发送时间FIFO控制，不存储
    TxHeader.MessageMarker = 0;                       // 识别消息状态，范围0到0xFF

    // 发送CAN消息
    if (HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan2, &TxHeader, data) != HAL_OK)
    {
        log_e("fdcan2 send faiil.");
        // Error_Handler();
    }
    return ret;
}

/**
 * @brief stm32 CAN的底层驱动初始化
 * @return int 
 */
int stm32_can_start(void)
{
    int ret = 0;

    HAL_FDCAN_ActivateNotification(&hfdcan1, FDCAN_IT_RX_FIFO0_NEW_MESSAGE, 0); // 使能FIFO0数据接收中断
    HAL_FDCAN_ActivateNotification(&hfdcan2, FDCAN_IT_RX_FIFO0_NEW_MESSAGE, 0); // 使能FIFO0数据接收中断
    HAL_FDCAN_Start(&hfdcan1);
    HAL_FDCAN_Start(&hfdcan2);
    return ret;
}
